package com.yx.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Classname MybatisUtil
 * @Description TODO:Mybatis工具类
 * @Date 2021/05/14 18:50
 * @Created by yx
 */
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    public static final ThreadLocal<SqlSession> THREAD_LOCA = new ThreadLocal<>();

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession(){
        SqlSession sqlSession = THREAD_LOCA.get();
        if (sqlSession == null) {
            sqlSession=sqlSessionFactory.openSession();
            THREAD_LOCA.set(sqlSession);
        }
        return sqlSession;
    }


    public static void commit(){
        SqlSession sqlSession = getSession();
        sqlSession.commit();
        closeSession();
    }

    public static void rollback(){
        SqlSession sqlSession = getSession();
        sqlSession.rollback();
        closeSession();
    }

    public static void closeSession(){
        SqlSession sqlSession = getSession();
        sqlSession.close();
        THREAD_LOCA.remove();
    }

    public static <T> T getMapper(Class<T> clazz){
        SqlSession sqlSession = getSession();
        T mapper = sqlSession.getMapper(clazz);
        return mapper;
    }
}
